package com.edu.quartz.service;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.edu.common.core.cache.ICache;
import com.edu.quartz.config.NicezhuanyeConfig;
import java.io.IOException;
import java.time.Duration;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import javax.annotation.Resource;
import javax.validation.constraints.NotNull;
import lombok.extern.slf4j.Slf4j;
import okhttp3.Call;
import okhttp3.EventListener;
import okhttp3.FormBody;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;

/**
 * @program: xxxx_2
 * @description:
 * @author: zlh
 * @create: 2024-01-11 19:48
 **/
@Slf4j
@Service
public class NicezhuanyeFactory {

  @Resource
  private NicezhuanyeConfig nicezhuanyeConfig;
  @Resource
  private ICache iCache;

  private static final String tokenKey = "nicezhuanye_token";

  public OkHttpClient niceHttpClient(){
    String token = this.getAccessToken();
    return new OkHttpClient.Builder()
        .connectTimeout(Duration.ofSeconds(30))
        .readTimeout(Duration.ofSeconds(60))
        .callTimeout(Duration.ofSeconds(120))
        .addInterceptor(
            new Interceptor() {
              @Override
              public Response intercept(Interceptor.Chain chain) throws IOException {
                Request originalRequest = chain.request();
                Request newRequest = originalRequest.newBuilder()
                    .header("Authorization", token)
                    .build();
                return chain.proceed(newRequest);
              }
            }
        )
        // 注册事件监听器
        .eventListener(new EventListener() {
          @Override
          public void callEnd(@NotNull Call call) {
            log.info("----------callEnd--------");
            super.callEnd(call);
          }
        })
        .build();
  }

  public String getAccessToken(){
//    String token = iCache.getCacheObject(tokenKey);
//    if (StrUtil.isBlank(token)){
//      token = this.createAccessToken();
//      iCache.setCacheObject(tokenKey, token, 250, TimeUnit.SECONDS);
//    }
//    return token;

    return this.createAccessToken();
  }

  public String createAccessToken(){

    OkHttpClient client = new OkHttpClient.Builder().build();
    RequestBody formBody = new FormBody.Builder()
        .add("grant_type", "client_credentials")
        .add("appKey", nicezhuanyeConfig.getAppKey())
        .add("appSecret", nicezhuanyeConfig.getSecretKey())
        .build();
    Request request = new Request.Builder()
        .url(nicezhuanyeConfig.getTokeUri())
        .post(formBody)
        .build();
    try {
      Response response = client.newCall(request).execute();

      if (response.isSuccessful()) {
        String resp = response.body().string();
        JSONObject jsonObject = JSON.parseObject(resp);
        log.info("获取accessToken 返回：{}" , resp);
        if ("success".equals(jsonObject.get("status"))) {
          JSONObject result = jsonObject.getJSONObject("result");
          if (null != result) {
            return result.getString("access_token");
          }
        }
      }
    } catch (Exception e){
      log.error("获取accessToken 异常：{}", e.getMessage(), e);
    }

    return null;
  }




}
